package alidns

import (
	"sync"

	alidns20150109 "github.com/alibabacloud-go/alidns-20150109/v2/client"
	openapi "github.com/alibabacloud-go/darabonba-openapi/client"
	"github.com/alibabacloud-go/tea/tea"
)

var client *Client
var once sync.Once

type Client struct {
	aliClient *alidns20150109.Client
}

func NewClient(accessKeyId *string, accessKeySecret *string) (client *Client, _err error) {
	once.Do(func() {
		client = &Client{}
		config := &openapi.Config{
			AccessKeyId:     accessKeyId,
			AccessKeySecret: accessKeySecret,
			Endpoint:        tea.String("dns.aliyuncs.com"),
		}
		client.aliClient, _err = alidns20150109.NewClient(config)
		if _err != nil {
			panic(_err)
		}
	})
	return client, _err
}
func (c *Client) AddRecord(domain *string, rr *string, value *string) (_result *alidns20150109.AddDomainRecordResponseBody, _err error) {
	request := &alidns20150109.AddDomainRecordRequest{
		DomainName: domain,
		RR:         rr,
		Type:       tea.String("A"),
		Value:      value,
	}
	response, _err := c.aliClient.AddDomainRecord(request)
	return response.Body, _err
}

func (c *Client) GetRecords(domain string, rr string) (_result []*alidns20150109.DescribeSubDomainRecordsResponseBodyDomainRecordsRecord, _err error) {
	request := &alidns20150109.DescribeSubDomainRecordsRequest{
		SubDomain: tea.String(rr + "." + domain),
		Type:      tea.String("A"),
		PageSize:  tea.Int64(500),
	}
	response, _err := c.aliClient.DescribeSubDomainRecords(request)
	return response.Body.DomainRecords.Record, _err
}

func (c *Client) UpdateRecord(recordId *string, rr *string, value *string) (_result *alidns20150109.UpdateDomainRecordResponseBody, _err error) {
	request := &alidns20150109.UpdateDomainRecordRequest{
		RecordId: recordId,
		RR:       rr,
		Type:     tea.String("A"),
		Value:    value,
	}
	response, _err := c.aliClient.UpdateDomainRecord(request)
	return response.Body, _err
}

func (c *Client) DeleteRecord(recordId *string) (_result *alidns20150109.DeleteDomainRecordResponseBody, _err error) {
	request := &alidns20150109.DeleteDomainRecordRequest{
		RecordId: recordId,
	}
	response, _err := c.aliClient.DeleteDomainRecord(request)
	return response.Body, _err
}
